package com.ly.mp.cmc.common.filter;

import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @Author: ly-songpengfei
 * @Date: 2025/8/5 12:08
 * @Description: web过滤器
 * @Version: 1.0
 */
// 方式一：实现Filter中的方法，但是要在项目中注册Filter/使用@WebFilter("/")
//public class WebFilter implements Filter {
//
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//
//    }
//
//}

// 方式二：继承OncePerRequestFilter，重写doFilterInternal方法
@Component
public class WebFilter extends OncePerRequestFilter {

    public WebFilter() {
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader("Authorization");
        String token = request.getHeader("token");
        authorization = !StringHelper.isNullOrEmptyString(authorization) ? authorization :
                (!StringHelper.isNullOrEmptyString(token) ? token : "");
        token = request.getParameter("token");
        authorization = !StringHelper.isNullOrEmptyString(authorization) ? authorization :
                (!StringHelper.isNullOrEmptyString(token) ? token : "");

        if (!StringHelper.isNullOrEmptyString(authorization)) {
            HashMap<String, Object> param = new HashMap();
            param.put("token", authorization);
            RequestParameterWrapper requestParameterWrapper = new RequestParameterWrapper(request, param);
            System.out.println("requestParameterWrapper");
            filterChain.doFilter(requestParameterWrapper, response);
        } else {
            System.out.println("request");
            filterChain.doFilter(request, response);
        }
    }

}